/*
 * Copyright © 2011-2015 Kinghood Group All Rights Reserved.
 * 未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 * 版权所有深圳金雅福控股集团有限公司 www.jinyafu.com.
 */
package com.kinghood.obs;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO:Obs管理类
 * @version 2019年2月14日上午11:45:40
 * @author Mike
 */
@Slf4j
@Component
public class ObsManger {
	
	@Resource
	private ObsClient obsClient;
	@Autowired
	ObsProperties obsProperties;

	public final int OKCODE = 0;
	public final String OKMESSAGE = "成功";

	/**
	 * 
	 * TODO:根据url地址上传
	 * @version 2019年2月14日下午4:36:11
	 * @author Mike
	 * @param url
	 * @param objectKey
	 * @return
	 */
	public synchronized Map<String,Object> netWorkUpload(String url,String objectKey, String bucketName) {
		if(StringUtils.isBlank(bucketName)){
            bucketName=obsProperties.getBucketName();
		}
		Map<String,Object> map = new HashMap<String,Object>();
			InputStream inputStream;
			try {
				inputStream = new URL(url).openStream();
				obsClient.putObject(obsProperties.getBucketName(), objectKey, inputStream);
				map.put("Message", OKMESSAGE);
				map.put("Code", OKCODE);
			} catch (MalformedURLException e) {
				map.put("Message", e.getMessage());
				map.put("Code", "500");
			} catch (IOException e) {
				map.put("Message", e.getMessage());
				map.put("Code", "500");
			} catch (ObsException e) {
				map.put("Message", e.getErrorMessage());
				map.put("Code", e.getErrorCode());
			}
		
		return map;
	}
	
	/**
	 * 
	 * TODO:文件上传
	 * @version 2019年2月14日下午4:36:27
	 * @author Mike
	 * @param file
	 * @param objectKey
	 * @return
	 */
	public synchronized Map<String,Object> fileUpload(MultipartFile file,String objectKey, String bucketName) {
		if(StringUtils.isBlank(bucketName)){
            bucketName=obsProperties.getBucketName();
		}
		Map<String,Object> map = new HashMap<String,Object>();
		InputStream fis;
			try {
			    fis = file.getInputStream();
				obsClient.putObject(bucketName, objectKey, fis);
				map.put("Message", OKMESSAGE);
				map.put("Code", OKCODE);
			} catch (IOException e) {
				map.put("Message", e.getMessage());
				map.put("Code", "500");
			} catch (ObsException e) {
				map.put("Message", e.getErrorMessage());
				map.put("Code", e.getErrorCode());
			}
		
		return map;
	}
	
	
	public  synchronized Map<String,Object> fileUpload(MultipartFile file,String objectKey) {
		Map<String,Object> map = new HashMap<String,Object>();
		InputStream fis;
			try {
			    fis = file.getInputStream();
				obsClient.putObject(obsProperties.getBucketName(), objectKey, fis);
				map.put("Message", OKMESSAGE);
				map.put("Code", OKCODE);
			} catch (IOException e) {
				map.put("Message", e.getMessage());
				map.put("Code", "500");
			} catch (ObsException e) {
				map.put("Message", e.getErrorMessage());
				map.put("Code", e.getErrorCode());
			}
		
		return map;
	}
	
	
	/**
	 * 
	 * TODO:批量删除
	 * @version 2019年8月27日下午6:30:06
	 * @author Mike
	 * @param objectKey
	 * @return
	 */
	public synchronized Map<String,Object> deleteFile(String bucketName,List<String> objectKey) {
		if(StringUtils.isBlank(bucketName)){
            bucketName=obsProperties.getBucketName();
		}
		Map<String,Object> map = new HashMap<String,Object>();
			try {
			    DeleteObjectsRequest dor = new DeleteObjectsRequest(bucketName);
			    for (String filePath : objectKey) {
			    	dor.addKeyAndVersion(filePath);
				}
			    DeleteObjectsResult deleteResult=  obsClient.deleteObjects(dor);
			    // 获取删除成功的对象
			    log.info("调用成功结果：{}",deleteResult.getDeletedObjectResults());
			    
			    if(!CollectionUtils.isEmpty(deleteResult.getErrorResults())) {
			    	log.error("删除失败结果：{}",deleteResult.getErrorResults());
			    }
				map.put("Message", OKMESSAGE);
				map.put("Code", OKCODE);
			} catch (ObsException e) {
				map.put("Message", e.getErrorMessage());
				map.put("Code", e.getErrorCode());
			}
		
		return map;
	}
	
	
	/**
	 * 
	 * TODO:本地文件上传
	 * @version 2019年2月20日下午4:51:28
	 * @author Mike
	 * @param file
	 * @param objectKey
	 * @return
	 */
	public  synchronized Map<String,Object> fileUpload(File file,String objectKey, String bucketName ) {
		if(StringUtils.isEmpty(bucketName)){
            bucketName=obsProperties.getBucketName();
		}
		Map<String,Object> map = new HashMap<String,Object>();
		FileInputStream fis;
			try {
			    fis = new FileInputStream(file);
				PutObjectResult result =  obsClient.putObject(bucketName, objectKey, fis);
				log.info("obs result:{}", result);
				map.put("Message", OKMESSAGE);
				map.put("Code", OKCODE);
			} catch (IOException e) {
				map.put("Message", e.getMessage());
				map.put("Code", "500");
			} catch (ObsException e) {
				map.put("Message", e.getErrorMessage());
				map.put("Code", e.getErrorCode());
			}
		
		return map;
	}


	/**
	 * 本地文件上传
	 *
	 * @param localFile 加载文件
	 * @param savePath 保存的对象地址
	 * @author zfj
	 * @date 2024/1/23
	 */
	public synchronized Boolean fileUpload(String localFile,String savePath){

		try {
			PutObjectResult res = obsClient.putObject(obsProperties.getBucketName(), savePath, new File(localFile));
			log.info("文件上传，加载文件：{}，上传结果：{}",localFile,res);
			return true;
		} catch (ObsException e) {
			log.error("文件上传失败：",e);
		} catch (Exception e) {
			log.error("文件上传其他异常：",e);
		}
		return false;
	}
	
	/**
	 * 
	 * TODO:创建文件夹
	 * @version 2019年2月19日下午6:42:06
	 * @author Mike
	 * @param folderName
	 * @return
	 */
	public  synchronized Map<String,Object> createFolder(String folderName, String bucketName ) {
		if(StringUtils.isEmpty(bucketName)){
            bucketName=obsProperties.getBucketName();
		}
		Map<String,Object> map = new HashMap<String,Object>();
			try {
				obsClient.putObject(bucketName, folderName,new ByteArrayInputStream(new byte[0]));
				map.put("Message", OKMESSAGE);
				map.put("Code", OKCODE);
			}  catch (ObsException e) {
				map.put("Message", e.getErrorMessage());
				map.put("Code", e.getErrorCode());
			}
		return map;
	}
	
	/**
	 * 
	 * TODO:文件下载
	 * @version 2019年2月21日上午11:10:51
	 * @author Mike
	 * @param objectkey
	 * @return
	 */
	public  synchronized InputStream downFile(String bucketName,String objectkey ) {
		if(StringUtils.isEmpty(bucketName)){
            bucketName=obsProperties.getBucketName();
		}
		ObsObject obsObject = obsClient.getObject(bucketName, objectkey);
		if(obsObject == null) return null;
		return  obsObject.getObjectContent();
	}
	
	/**
	 * TODO:获取签名
	 * @date 2020年7月22日下午5:13:49
	 * @author Mike
	 * @param bucketName
	 * @return
	 */
	 public Map<String,String> getSign(String bucketName) {
		 	log.info("请求obs签名，签名值,请求桶：{}"+bucketName);
		 	if(StringUtils.isEmpty(bucketName)){
	           bucketName=obsProperties.getBucketName();
			}
	        PostSignatureRequest request = new PostSignatureRequest();
	        // 设置表单参数
	        Map<String, Object> formParams = new HashMap<String, Object>();
	        // 设置对象访问权限为公共读
	        formParams.put("x-obs-acl", "public-read");
	        // 设置对象MIME类型
	        formParams.put("content-type", "text/plain");
	        request.setFormParams(formParams);
	        // 设置表单上传请求有效期，单位：秒
	        request.setExpires(3600);
	        PostSignatureResponse response = obsClient.createPostSignature(request);
	        log.info("OBS请求清明返回值:{}",response);
	        // 获取表单上传请求参数
	        Map<String,String> map = new HashMap<String,String>();
	        map.put("ak", obsProperties.getAccessKey());
	        map.put("sk", obsProperties.getSecrtKey());
	        map.put("endpoint", obsProperties.getEndpoint());
	        map.put("bucketName", bucketName);
	        map.put("policy", response.getPolicy());
	        map.put("signature", response.getSignature());        
	        return map;
	    }


}
